<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入帖子标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择分类" clearable>
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:post:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="帖子ID" align="center" prop="postId" />
      <el-table-column label="标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="分类" align="center" prop="category">
        <template slot-scope="scope">
          <span>{{ scope.row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="images" width="120">
        <template slot-scope="scope">
          <div v-if="scope.row.images" class="image-preview">
            <el-image 
              style="width: 50px; height: 50px; margin-right: 2px"
              :src="scope.row.images.split(',')[0]"
              :preview-src-list="scope.row.images.split(',')"
            >
            </el-image>
            <el-tag v-if="scope.row.images.split(',').length > 1" size="mini" type="info" style="position: absolute; right: 2px; bottom: 2px">
              +{{ scope.row.images.split(',').length - 1 }}
            </el-tag>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="点赞数" align="center" prop="likes" />
      <el-table-column label="评论数" align="center" prop="comments" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:post:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改帖子对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="form.category" placeholder="请选择分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="6" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <el-upload
            :action="upload.url"
            :headers="upload.headers"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :file-list="fileList"
            multiple
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看帖子详情对话框 -->
    <el-dialog title="帖子详情" :visible.sync="viewOpen" width="780px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="帖子ID">{{ viewForm.postId }}</el-descriptions-item>
        <el-descriptions-item label="标题">{{ viewForm.title }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewForm.category }}</el-descriptions-item>
        <el-descriptions-item label="内容">
          <div style="white-space: pre-wrap;">{{ viewForm.content }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="图片">
          <div v-if="viewForm.images">
            <el-image
              v-for="(image, index) in viewForm.images.split(',')"
              :key="index"
              style="width: 200px; height: 200px; margin-right: 10px; margin-bottom: 10px;"
              :src="image"
              :preview-src-list="viewForm.images.split(',')"
            >
            </el-image>
          </div>
          <span v-else>无图片</span>
        </el-descriptions-item>
        <el-descriptions-item label="点赞数">{{ viewForm.likes }}</el-descriptions-item>
        <el-descriptions-item label="评论数">{{ viewForm.comments }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewForm.createTime) }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, delPost, addPost, updatePost } from '@/api/business/post'
import { getToken } from '@/utils/auth'

export default {
  name: 'Post',
  dicts: ['post_category'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 帖子表格数据
      postList: [],
      // 所有帖子数据
      allPosts: [],
      // 分类选项
      categoryOptions: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        category: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '分类不能为空', trigger: 'change' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' }
        ]
      },
      // 图片上传相关
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
      uploadedImages: [], // 新增：存储上传的图片URL数组
      // 是否显示查看弹出层
      viewOpen: false,
      // 查看表单参数
      viewForm: {},
      // 上传参数
      upload: {
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        headers: { Authorization: 'Bearer ' + getToken() }
      }
    }
  },
  created() {
    this.getAllPosts()
  },
  methods: {
    /** 获取所有帖子数据 */
    async getAllPosts() {
      try {
        const response = await listPost({ pageSize: 9999 })
        this.allPosts = response.rows
        this.processOptions()
        this.getList() // 获取分页数据
      } catch (error) {
        console.error('获取帖子数据失败:', error)
        this.$modal.msgError('获取帖子数据失败')
      }
    },

    /** 处理下拉框选项 */
    processOptions() {
      // 处理分类选项
      const categorySet = new Set()
      this.allPosts.forEach(post => {
        if (post.category) {
          categorySet.add(post.category)
        }
      })
      this.categoryOptions = Array.from(categorySet).map(category => ({
        value: category,
        label: category
      }))
    },

    /** 查询帖子列表 */
    getList() {
      this.loading = true
      listPost(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.postList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        postId: null,
        title: null,
        content: null,
        category: null,
        images: null,
        likes: 0,
        comments: 0,
        status: '0'
      }
      this.fileList = []
      this.uploadedImages = [] // 重置上传的图片数组
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加帖子'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const postId = row.postId || this.ids
      getPost(postId).then(response => {
        this.form = response.data
        // 如果有图片，添加到文件列表
        if (this.form.images) {
          const imageUrls = this.form.images.split(',');
          this.uploadedImages = imageUrls;
          this.fileList = imageUrls.map(url => ({
            name: '已上传图片',
            url: url
          }));
        }
        this.open = true
        this.title = '修改帖子'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.postId != null) {
            updatePost(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addPost(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids
      this.$modal.confirm('是否确认删除帖子编号为"' + postIds + '"的数据项？').then(function() {
        return delPost(postIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    // 文件上传成功处理
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.uploadedImages.push(response.url)
        this.form.images = this.uploadedImages.join(',')
        this.$modal.msgSuccess('上传成功')
      } else {
        this.$modal.msgError('上传失败')
      }
    },
    // 文件上传失败处理
    handleUploadError() {
      this.$modal.msgError('上传失败')
    },
    // 文件移除处理
    handleRemove(file, fileList) {
      const fileUrl = file.url || file.response.url;
      const index = this.uploadedImages.indexOf(fileUrl);
      if (index > -1) {
        this.uploadedImages.splice(index, 1);
        this.form.images = this.uploadedImages.join(',');
      }
      this.fileList = fileList;
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewForm = row
      this.viewOpen = true
    }
  }
}
</script>

<style scoped>
.image-preview {
  position: relative;
  display: inline-block;
}

.image-preview .el-image {
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
}

.image-preview .el-tag {
  padding: 0 4px;
  height: 16px;
  line-height: 16px;
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  color: #fff;
}
</style> 